package pl
{
	import pl.engine.IIsoEngine;
	import pl.engine.IsoEngine;
	import pl.engine.ui.UI;
	import pl.world.actors.AnimatedActor;
	import pl.world.actors.IAnimatedActor;
	import pl.world.actors.proto.IActor;

	import starling.display.DisplayObject;
	import starling.display.Sprite;
	import starling.events.Event;

	import flash.geom.Point;

	/**
	 * @author michalr
	 */
	public class Game extends Sprite
	{
		private var isoEngine:IIsoEngine;
		private var cActor:IActor;
		private var actor:IActor;

		public function Game()
		{
			super();
			addEventListener( Event.ADDED_TO_STAGE, onATS );
		}

		private function onATS( event:Event ):void
		{
			showGame();
		}

		private function showGame():void
		{
			UI.registerStage( stage );
			isoEngine = new IsoEngine();
			isoEngine.generateDefaultTerain( 50, 50 );
			addChild( isoEngine as DisplayObject );
			//
			addActors();
			var actor:IActor = new AnimatedActor( 100, 100, 0, 0, 10 );
			cActor = actor;
			isoEngine.addActor( actor );
			UI.registerUIHandlers( onUIClick, onUIMouseMove );
		}

		private function onUIMouseMove():void
		{
			if (UI.getCursorMode() == UI.DRAG)
			{
				isoEngine.updateWorld();
			}
		}

		private function addActors():void
		{
			var i:uint = 0;
			var n:uint = 5;
			var mp:Vector.<Point>;
			var j:uint = 5;
			while (i < n)
			{
				actor = new AnimatedActor( 200 + Math.random() * 100, 200 + Math.random() * 150, 0, 0, Math.round( 1 + Math.random() * 6 ) );
				mp = new Vector.<Point>;

				mp.push( new Point( actor.x, actor.y ) );
				j = 10;
				while (j > 0)
				{
					mp.push( new Point( actor.x + 500 * Math.random(), actor.y + 500 * Math.random() ) );
					j--;
				}
				(actor as IAnimatedActor).setMovePath( mp );
				isoEngine.addActor( actor );
				i++;
			}
		}

		private function onUIClick():void
		{
			var rp:Point = isoEngine.positionRectUnderCursor;
			var p:Point = (rp).clone();
			p.x -= (cActor).x;
			p.y -= (cActor).y;

			var angle:Number = Math.atan2( p.y, p.x );
			var angleD:Number = angle * 180 / Math.PI - 45;

		
			if (UI.cursor.isReleased == true && UI.getCursorMode() == UI.SELECT)
			{
				if (cActor != null)
				{
					isoEngine.moveActorTo( cActor, rp );
				}
			}
		}
	}
}
